<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Template;
use app\api\model\v1\TemplateDetail;
use app\api\model\v1\TemplateSample;
use app\api\model\v1\TemplateSecondLevel;
use app\api\model\v1\TemplateType;
use app\api\validate\v1\TemplateSampleValidate;
use app\api\validate\v1\TemplateValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\Request;

class TemplateCon extends BaseController
{

    use SearchDataForModel, FileUpload;


    /**
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 10:56
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 数据列表
     */
    public function templateList()
    {
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type', '1');
        $res = Template::paginate($limit);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/10
     * @Time: 17:57
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 导入样本模版
     */
    public function templateSampleList(){
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type', '1');
        $res = TemplateSample::paginate($limit);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 10:54
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增and编辑
     */
    public function saveTemplate()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                TemplateValidate::rules($id),
                TemplateValidate::msg());
            if ($validator) {
                $data = $this->request->param();
                $data['create_id'] = $this->request->uid;
                if (intval($id) === 0) {
                    Template::create($data);
                } else {
                    $template = Template::find($id);
                    $template->save($data);
                }
                //日志
                AdminLog::record(intval($id) === 0 ? '新增模版' : '编辑模版', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            }
        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/10
     * @Time: 18:04
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增编辑样本点模版
     */
    public function saveSampleTemplate()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                TemplateSampleValidate::rules($id),
                TemplateSampleValidate::msg());
            if ($validator) {
                $data = $this->request->param();
                $data['create_id'] = $this->request->uid;
                if (intval($id) === 0) {
                    TemplateSample::create($data);
                } else {
                    $template_sample = TemplateSample::find($id);
                    $template_sample->save($data);
                }
                //日志
                AdminLog::record(intval($id) === 0 ? '新增模版样本点' : '编辑模版样本点', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            }
        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 11:14
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除模版
     */
    public function templateDel($id)
    {
        $res = Template::with(['templateType', 'templateSecondLevel', 'templateDetail'])->find($id);
        if (is_null($res)) {
            return $this->response(501, '无法找到该模版');
        }
        $res->together(['templateType', 'templateSecondLevel', 'templateDetail'])->force()->delete();
        //日志
        AdminLog::record('删除模版', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/11/10
     * @Time: 18:06
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除模版样本点
     */
    public function templateSampleDel($id)
    {
        $res = TemplateSample::find($id);
        if (is_null($res)) {
            return $this->response(501, '无法找到该样本');
        }
        $res->force()->delete();
        //日志
        AdminLog::record('删除样本点模版', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }
    /**
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 14:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 导入问卷
     */
    public function importExcel()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $id = $this->request->param('id');
        $template = Template::where(['is_upload'=>1])->find($id);

        $year = $this->request->param('year');
        if (is_null($template)){
            $result = $this->saveImportExcel($file, 'import_excel');
            $is_bool = Template::saveExcel($result, $id, $year, $this->request->uid);
            if ($is_bool === 200) {
                //日志
                AdminLog::record('导入模版', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            } else if ($is_bool === 403) {
                return $this->response(403, '未找到您选择的模版');
            } else {
                return $this->response(403, '导入问卷失败');
            }
        }else{
            return $this->response(403, '问卷已存在,请不要重复上传');
        }

    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/10
     * @Time: 17:56
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 导入样本点模版
     */
    public function importSampleExcel(){
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->saveImportExcel($file, 'import_sample_excel','sample');
        $is_bool = TemplateSample::saveSampleExcel($result, $this->request->uid);
        if ($is_bool === 200) {
            //日志
            AdminLog::record('导入样本模版', $this->request->param(), $this->request->uid, $this->request->username);
            return $this->response();
        }else {
            return $this->response(403, '导入样本失败');
        }
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 15:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 监测是否存在数据
     */
    public function checkQuestion($id)
    {
        $res = Template::with(['templateType'])->find($id);
        if (is_null($res)) {
            return $this->response(501, '无法找到该模版');
        }
        $type = $res['templateType']->toArray();
        if (empty($type)) {
            return $this->response(501, '暂无数据,无法打开');
        }
        return $this->response($type);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 15:15
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 根据模版id 获取对应的分类
     */
    public function templateTypeList()
    {
        $limit = $this->request->param('limit', 10);
        $id = $this->request->param('id');
        $map[] = array('template_id', '=', $id);
        $res = $this->search(new TemplateType(), $map, $limit, 'asc', ['templateSecondLevel.templateDetail']);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 17:26
     * @return \think\response\Json
     * 更新详情模版数据
     */
    public function updateDetailTemplate()
    {
        $data = $this->request->param();

        TemplateDetail::update($data);
        //日志
        AdminLog::record('更新模版详情', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 17:39
     * @return \think\response\Json
     * 大类别更新
     */
    public function updateTemplate()
    {
        $data = $this->request->param();
        TemplateType::update([
            'id' => $data['id'],
            'template_type_title' => $data['template_type_title']
        ]);
        //日志
        AdminLog::record('更新模版类别', $this->request->only(['id', 'template_type_title']), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/24
     * @Time: 17:56
     * @return \think\response\Json
     * 二级类别更新
     */
    public function updateSecondLevel()
    {
        $data = $this->request->param();
        TemplateSecondLevel::update([
            'id' => $data['id'],
            'second_level_title' => $data['second_level_title']
        ]);
        //日志
        AdminLog::record('更新模版二级类别', $this->request->only(['id', 'second_level_title']), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/25
     * @Time: 9:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增
     */
    public function addTemplate()
    {
        $data = $this->request->param();
        $template = Template::find($data['template_id']);
        if (is_null($template)) {
            return $this->response(403, '暂未找到该模版问卷,新增失败！');
        }
        if ($data['is_type_create'] && $data['is_second_create']) { //两者都是真
            //如果1级分类和二级分类都是新增的话
            $template_type_id = TemplateType::create(['template_type_title' => $data['type'], 'year' => $template['year'], 'template_id' => $data['template_id']])->id; //先创建1级分类并获取对应的新增id
            //二级分类
            $template_second_level_id = TemplateSecondLevel::create([
                'second_level_title' => $data['second'],
                'year' => $template['year'],
                'template_id' => $data['template_id'],
                'template_type_id' => $template_type_id
            ])->id;
        } else if ($data['is_type_create'] && $data['is_second_create'] === false) { //一级为真的时候
            //如果1级分类和二级分类都是新增的话
            $template_type_id = TemplateType::create(['template_type_title' => $data['type'], 'year' => $template['year'], 'template_id' => $data['template_id']])->id; //先创建1级分类并获取对应的新增id
            $template_second_level_id = $data['second'];
        } else if ($data['is_type_create'] === false && $data['is_second_create']) { //二级为真的时候
            $template_type_id = $data['type'];
            $template_second_level_id = TemplateSecondLevel::create([
                'second_level_title' => $data['second'],
                'year' => $template['year'],
                'template_id' => $data['template_id'],
                'template_type_id' => $template_type_id
            ])->id;
        } else { //都为false的时候
            $template_type_id = $data['type'];
            $template_second_level_id = $data['second'];
        }

        $new_data = [
            'template_detail_title' => $data['template_detail_title'] ?? '',
            'year' => $template['year'] ?? '',
            'desc' => $data['desc'] ?? '',
            'deduct_marks_standard' => $data['deduct_marks_standard'] ?? '',
            'once_deduct_marks' => $data['once_deduct_marks'] ?? '',
            'most_deduct_marks' => $data['most_deduct_marks'] ?? '',
            'template_id' => $data['template_id'],
            'template_type_id' => $template_type_id,
            'template_second_level_id' => $template_second_level_id,
            'create_id' => $this->request->uid
        ];
        TemplateDetail::create($new_data);
        //日志
        AdminLog::record('新增问卷模版', $new_data, $this->request->uid, $this->request->username);
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/25
     * @Time: 9:26
     * 下载模版
     */
    public function downloadFile()
    {
        $file = public_path() . 'storage/template/demo.xlsx';
        $data = $this->downloadExcel($file);
        return $data;
    }

//    //随机生成
//    public function randomTemplate($id)
//    {
//        $res = Template::find($id);
//        if (is_null($res)) {
//            return $this->response(403, '无法找到模版问卷');
//        }
//        $num = 3; //定义随机抽取的数量
//        //根据问卷id找到一级大类
//        $template_type = TemplateType::with(['templateSecondLevel' => ['templateDetail']])->where(['template_id' => $id])->select()->toArray();
//        if ($num <= 1) {
//            return $this->response(403, '随机抽取数量必须大于1');
//        } else if ($num <= count($template_type)) {
//            $rand = array_rand($template_type, $num);
//            $new_arr = [];
//            for ($i = 0; $i < $num; $i++) {
//                $new_arr[] = $template_type[$rand[$i]];
//                if (count($template_type[$rand[$i]]['templateSecondLevel']) > $num) {
//                    $abc = array_rand($template_type[$rand[$i]]['templateSecondLevel'], $num);
//                    $abc_new_arr = [];
//                    for ($j = 0; $j < count($abc); $j++) {
//                        $abc_new_arr[] = $template_type[$rand[$i]]['templateSecondLevel'][$abc[$j]];
//                    }
//                    $new_arr[$i]['templateSecondLevel'] = $abc_new_arr;
//                } else {
//                    $new_arr[$i]['templateSecondLevel'] = $template_type[$rand[$i]]['templateSecondLevel'];
//                }
//            }
////            halt($template_type[$rand[0]]);
////            //根据大类别的情况下随机抽取数据
////            $second_map = [];
////            $second_map[] = array('template_type_id', 'in', $one_id_arr); //二级条件
////            $template_second_level = TemplateSecondLevel::where($second_map)->select()->toArray();
////
////            $rand_second = array_rand($template_second_level, $num);
////            halt($template_second_level[$rand_second[0]]);
////            $second_arr = array();
////            $second_id_arr = array();
////            //二级
////            for ($i = 0; $i < $num; $i++) {
////                $second_arr[] = $template_second_level[$rand_second[$i]];
////                $second_id_arr[] = $template_second_level[$rand_second[$i]]['id'];
////            }
////            //三级
////            $detail_map = [];
////            $detail_map[] = array('template_second_level_id', 'in', $second_id_arr); //二级条件
////            $detail_res = TemplateDetail::where($detail_map)->select()->toArray();
////            //随机生成的数据插入数据库
//            return $new_arr;
////            return [
////                'one' => $one_arr,
////                'second' => $second_arr,
////                'detail' => $detail_res,
////            ];
//        } else {
//            return $this->response(403, '随机抽取数量大于当前题库存在的数量');
//        }
//    }


//    //生成所有
//    public function templateAllCreate()
//    {
//        $id = $this->request->param('id', 1);
//        $res = Template::with(['templateType' => ['templateSecondLevel' => ['templateDetail']]])->find($id);
//        if (is_null($res)) {
//            return $this->response(403, '无法找到模版问卷');
//        }
//        //循环即可
//        halt(json_encode($res));
//    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/11
     * @Time: 9:49
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * select选择模版
     */
    public function getTemplateSelect(){
        $res = Template::where(['is_upload'=>1,'status'=>1])->select();
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/26
     * @Time: 17:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取二级模版
     */
    public function getTwoTemplate()
    {
        $id_arr = $this->request->param('id_arr');
        if (empty($id_arr)) {
            return $this->response(403, '无法找到模版问卷');
        }
        $second_map = [];
        $second_map[] = array('id', 'in', $id_arr); //二级条件
        $res = TemplateType::with(['templateSecondLevel'])->where($second_map)->select()->toArray();
        //$res = TemplateSecondLevel::with(['templateType'])->where($second_map)->select()->toArray();

        return $this->response($res);

    }


}
